package com.rx.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.rx.common.DBUtils;
import com.rx.entity.Role;

public class RoleDaoImpl implements RoleDaoI<Role> {

	@Override
	public boolean insert(Role role) throws Exception {
		Connection conn = DBUtils.getConnection();
		String sql = "INSERT INTO role (roleName,remark) VALUES(?,?)";
		PreparedStatement ps = conn.prepareStatement(sql);
		ps.setString(1, role.getRoleName());
		ps.setString(2, role.getRemark());
		if (ps.executeUpdate() > 0) {
			return true;
		}
		return false;
	}

	@Override
	public boolean update(Role role) throws Exception {
		Connection conn = DBUtils.getConnection();
		String sql = "UPDATE role SET roleName=?,remark=? WHERE id=?";
		PreparedStatement ps = conn.prepareStatement(sql);
		ps.setString(1, role.getRoleName());
		ps.setString(2, role.getRemark());
		ps.setInt(3, role.getId());
		if (ps.executeUpdate() > 0) {
			return true;
		}

		return false;
	}

	@Override
	public boolean delete(int id) throws Exception {
		Connection conn = DBUtils.getConnection();
		String sql = "DELETE FROM role WHERE id=?";
		PreparedStatement ps = conn.prepareStatement(sql);
		ps.setInt(1, id);
		if (ps.executeUpdate() > 0) {
			return true;
		}
		return false;
	}

	@Override
	public List<Role> selectAll() throws Exception {
		Connection conn = DBUtils.getConnection();
		String sql = "SELECT * FROM role";
		PreparedStatement ps = conn.prepareStatement(sql);
		ResultSet rs = ps.executeQuery();
		List<Role> list = new ArrayList<>();
		while (rs.next()) {
			Role role = new Role();
			role.setId(rs.getInt(1));
			role.setRoleName(rs.getString(2));
			role.setRemark(rs.getString(3));
			list.add(role);
		}
		return list;
	}

	@Override
	public List<Role> selectWhere(String whereSql) throws Exception {
		Connection conn = DBUtils.getConnection();
		String sql = "SELECT id,roleName,remark FROM role WHERE 1=1 "+whereSql;
		PreparedStatement ps = conn.prepareStatement(sql);
		ResultSet rs = ps.executeQuery();
		List<Role> list = new ArrayList<>();
		while (rs.next()) {
			Role role = new Role();
			role.setId(rs.getInt(1));
			role.setRoleName(rs.getString(2));
			role.setRemark(rs.getString(3));
			list.add(role);
		}
		return list;
	}

}
